<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.orgId" class="filter-item" placeholder="选择机构" :clearable="true">
        <el-option
          v-for="(item,index) in OrgList"
          :key="index"
          :label="item.orgName"
          :value="item.id"
        />
      </el-select>
      <el-select v-model="listQuery.userType" class="filter-item" placeholder="用户类型" :clearable="true">
        <el-option
          v-for="(item,index) in empList"
          :key="index"
          :label="item.itemValue"
          :value="item.itemKey"
        />
      </el-select>
      <el-input v-model="listQuery.jobNumber" placeholder="工号" style="width: 100px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="序号" align="center" width="100">
        <template slot-scope="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像" prop="id" align="center">
        <template slot-scope="{row}">
          <img :src="row.photoUrl" style="width:100px;height:100px" alt="头像">
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.jobNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center">
        <template slot-scope="{row}">
          <span>{{ row.sex==='0'?'男':'女' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="部门" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orgId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row,$index)">
            修改
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="400px">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 100%;margin:0 auto">
        <!-- <el-form-item label="头像" prop="title">
          <dropzone id="myVueDropzone" style="text-align:center" url="https://httpbin.org/post" :defaultImg="temp.photoUrl" :thumbnail-width="120" :thumbnail-height="120" @dropzone-removedFile="dropzoneR" @dropzone-success="dropzoneS" />
        </el-form-item> -->
        <el-form-item label="头像上传" prop="title">
          <el-upload
            class="upload-demo"
            action="http://106.54.201.206:11000/api/resource/upload"
            :data="{module:'resource'}"
            :headers="fileHeader"
            name="fileName"
            :on-success="handleFileSuccess"
            :file-list="fileList"
            list-type="picture"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </el-form-item>
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="姓名" prop="title">
              <el-input v-model="temp.userName" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="工号" prop="title">
              <el-input v-model="temp.jobNumber" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="性别" prop="type">
              <el-select v-model="temp.sex" class="filter-item" placeholder="请选择">
                <el-option value="0" label="男">男</el-option>
                <el-option value="1" label="女">女</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="可登陆" prop="type">
              <el-select v-model="temp.allowLogin" class="filter-item" placeholder="请选择">
                <el-option value="0" label="是">是</el-option>
                <el-option value="1" label="否">否</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="员工类型" prop="type">
              <el-select v-model="temp.userType" class="filter-item" placeholder="请选择">
                <el-option
                  v-for="(item,index) in empList"
                  :key="index"
                  :label="item.itemValue"
                  :value="item.itemKey"
                />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="部门" prop="type">
              <!-- <el-select v-model="temp.orgId" class="filter-item" placeholder="请选择">
                <el-option
                  v-for="(item,index) in DepList"
                  :key="index"
                  :label="item.orgName"
                  :value="item.id"
                />
              </el-select> -->
              <el-cascader
                v-model="temp.deptId"
                style="width:100%"
                :options="DepList"
                :props="{ expandTrigger: 'hover',value:'deptId',label:'deptName',emitPath:false}"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageQuareApi, editApi, getByIdApi, addApi, DeleteApi } from '@/api/sysmanage'
import { getAllOrgList, getDicApi, getAllDeptList } from '@/api/public'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getToken } from '@/utils/auth'
export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      /* eslint-disable */
      value:'',
      empList:[],
      OrgList:[],
      DepList:[],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        userType: '',
        jobNumber:'',
        orgId:''
      },
      temp:  {
        "userName": "",
        "jobNumber": "",
        "userType": "",
        "sex": "0",
        "photoUrl": '',
        "deptId": '',
        "allowLogin":''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      updateObj:{
        index:'',
        data:[]
      },
       fileHeader:'',
      fileList: [],
    }
  },
  created() {
    this.getList()
    getDicApi({dictCode:'employee_type'}).then(res=>{
      const{data}=res
      this.empList=data
    })
    getAllOrgList().then(res=>{
      this.OrgList=res.data
    })
    getAllDeptList().then(res=>{
      this.DepList= this.digui(res.data)
      console.log("TCL: this.DepList", this.DepList)
    })
    let token=getToken('Admin-Token')
    this.fileHeader={
      token:token
    }
  },
  methods: {
     digui(arr){
        let _that=this
        if((!arr)||arr.length===0){
          return null
        }
        return arr.map((ele,index)=>{
          
          if((ele.deptName.indexOf('部门')==-1)&&!(ele.children)){
            ele.children=[]
            console.log(1)
          }else{
            ele.children=_that.digui(ele.children)
          }
          
          return ele
        })
      },
    // 头像上传
     handleFileSuccess(response, file, fileList){
      console.log("TCL: handleFileSuccess -> response", response)
      const {data}=response
      this.fileList=fileList
      this.temp.photoUrl=data.resourceUrl
    },
    dropzoneS(file) {
      console.log('TCL: dropzoneS -> dropzoneS', file)
      this.$message({ message: 'Upload success', type: 'success' })
    },
    dropzoneR(file) {
      console.log(file)
      this.$message({ message: 'Delete success', type: 'success' })
    },
    getList() {
      this.listLoading = true
      pageQuareApi (this.listQuery,'user').then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {//重置修改模态框
      this.temp = {
        "userName": "",
        "jobNumber": "",
        "userType": "",
        "sex": "0",
        "photoUrl": '',
        "deptId": '',
        "allowLogin":''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
       let _data= {
            "email":this.temp.email,
            "jobNumber": this.temp.jobNumber,
            "orgId": this.temp.orgId,
            "deptId": this.temp.deptId,
            "photoUrl": this.temp.photoUrl,
            "sex": this.temp.sex,
            "userName": this.temp.userName,
            "userType": this.temp.userType,
            "allowLogin":this.temp.allowLogin,
          }
        if (valid=true) {
          addApi(_data,'user').then((res) => {
            if(res.code==='200'){
              this.$message({
                message: res.message,
                type: 'success',
              })
               this.dialogFormVisible = false
               this.list.unshift(res.data)
              //  this.handleFilter()//刷新重新请求
            }
          })
        }
      })
    },
    handleUpdate(row,index) {
      
      getByIdApi({id:row.id},'user').then(res=>{
        this.temp = res.data
      }).catch()
      //保存修改的行数据，索引
      this.updateObj={
        index:index,
        data:row
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid=true) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          editApi(tempData,'user').then((res) => {
            this.dialogFormVisible = false
            if(res.code==='200'){
               this.$message({
                message: res.message,
                type: 'success',
              })
              const {index,data}=this.updateObj
              const row=Object.assign(data, this.temp)
              console.log("TCL: updateData -> row", row)
              this.list.splice(index,1,row)
            }else{
               this.$message({
                message: res.message||'修改失败',
                type: 'error'
              })
            }
           
          })
        }
      })
    },
    handleDelete(row,index) {
      this.$confirm('此操作不可逆, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(res => {
         DeleteApi({id:row.id},'user').then(res=>{
             this.$message({
                message: res.message,
                type: 'success'
              })
              this.list.splice(index,1)
          }).catch(err=>{
             this.$message({
                message:err.message,
                type: 'error'
              })
          })
      })
    },
  }
}
</script>
